package cn.pegasus.teamwork.manager.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.iyizhan.teamwork.base.util.MapToEntity;
import cn.iyizhan.teamwork.base.util.PageObject;
import cn.iyizhan.teamwork.base.util.ParameterEunm;
import cn.iyizhan.teamwork.base.util.ReMessage;
import cn.iyizhan.teamwork.base.util.file.FtpUtils;
import cn.iyizhan.teamwork.base.util.plist.Icon;
import cn.pegasus.teamwork.manager.entity.SysUcenterApps;
import cn.pegasus.teamwork.manager.service.SysUcenterAppsService;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigFiles;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigFilesUpdateInfo;
import cn.pegasus.teamwork.sysconfig.mapper.SysConfigFilesUpdateInfoMapper;
import cn.pegasus.teamwork.sysconfig.service.SysConfigFilesService;
import cn.pegasus.teamwork.sysconfig.service.SysConfigFilesUpdateInfoService;
import cn.pegasus.teamwork.util.PlistUtil;

/**
 * @ClassName: AppUpdateController
 * @Description: APP更新控制
 * @author buyuer
 * @date 2015年11月26日 下午5:47:55
 * 
 */
@RequestMapping("/appUpdate/*")
@Controller
public class AppUpdateController extends BaseManagerController<SysConfigFilesUpdateInfo, SysConfigFilesUpdateInfoMapper> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppUpdateController.class);

    @Autowired
    private SysConfigFilesUpdateInfoService infoService;

    @Autowired
    private SysConfigFilesService filesService;

    @Autowired
    private SysUcenterAppsService appsService;
    
    @RequestMapping("/updateInfoList")
    public ModelAndView updateInfoList(@RequestParam Map<String, Object> map) {
        ModelAndView view = new ModelAndView("appupdate/list-updateinfo");
        PageObject<SysConfigFilesUpdateInfo> object = infoService.Pagequery(map);
        view.addObject("updateInfoList", object);
        List<SysUcenterApps> apps =appsService.findAppsAll();
        view.addObject("apps", apps);
        return view;
    }

    @RequestMapping("/goAdd")
    public ModelAndView goAddUpdateInfo() {
        ModelAndView view = new ModelAndView("appupdate/add-updateinfo");
        List<SysUcenterApps> apps =appsService.findAppsAll();
        view.addObject("apps", apps);
        return view;
    }

    @ResponseBody
    @RequestMapping("/addInfo")
    public Map<String, Object> addUpdateInfo(@RequestParam Map<String, Object> map) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            SysConfigFilesUpdateInfo info = infoService.M2O(map);
            info.setCreateTime(new Date());
            info.setCreateUserBy(getAdmin().getId());
            infoService.add(info);
            resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, null);
        } catch (Throwable e) {
            LOGGER.error("删除失败.", e);
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, null);
        }
        return resultMap;
    }

    @ResponseBody
    @RequestMapping("/delInfo")
    public Map<String, Object> delUpdateInfo(@RequestParam(value = "id", required = true) Integer id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            infoService.delById(id);
            resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, null);
        } catch (Throwable e) {
            LOGGER.error("删除失败.", e);
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, null);
        }
        return resultMap;
    }

    @RequestMapping("/fileList")
    public ModelAndView fileList(@RequestParam Map<String, Object> map) {
        ModelAndView view = null;
        if (map != null && map.get("infoId") != null) {
            Integer infoId = Integer.parseInt(map.get("infoId").toString());
            SysConfigFilesUpdateInfo info = infoService.findById(infoId);
            view = new ModelAndView("appupdate/list-file");
            PageObject<SysConfigFiles> fileList = filesService.Pagequery(map);
            view.addObject("fileList", fileList);
            view.addObject("info", info);
        } else {
            view = new ModelAndView("404");
        }

        return view;
    }

    @RequestMapping("/toAddFiles")
    public ModelAndView toAddFile(@RequestParam(value = "infoId", required = true) Integer infoId) {
    	ModelAndView view = new ModelAndView("appupdate/add-file");
        SysConfigFilesUpdateInfo info = infoService.findById(infoId);
        view.addObject("info", info);
        return view;
    }
    
    @RequestMapping("/toEditFiles")
    public ModelAndView toEditFiles(@RequestParam(value = "infoId", required = true) Integer infoId,@RequestParam(value = "id", required = true) Integer id) {
    	ModelAndView view = new ModelAndView("appupdate/add-file");
    	view = new ModelAndView("appupdate/edit-file");
    	SysConfigFiles scf = new SysConfigFiles();
    	scf.setId(id);
    	SysConfigFiles files = filesService.detail(scf);
    	view.addObject("fileInfo", files);
        SysConfigFilesUpdateInfo info = infoService.findById(infoId);
        view.addObject("info", info);
        return view;
    }
    
    
    @ResponseBody
    @RequestMapping(value = "/addFiles.do")
    public Map<String, Object> addFiles(@RequestParam Map<String, Object> map) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        MapToEntity<SysConfigFiles> entity = new MapToEntity<SysConfigFiles>(SysConfigFiles.class, map);
        SysConfigFiles configFiles = entity.getEntity();
        if (configFiles != null) {
            configFiles.setCreateUserBy(getAdmin().getId());
            configFiles.setCreateTime(new Date());
            filesService.add(configFiles);
            resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, "保存成功！");
        } else {
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_PARAMS_CODE, "文件丢失了！");
        }
        return resultMap;
    }
    
    @ResponseBody
    @RequestMapping(value = "/editFiles.do")
    public Map<String, Object> editFiles(@RequestParam Map<String, Object> map) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        MapToEntity<SysConfigFiles> entity = new MapToEntity<SysConfigFiles>(SysConfigFiles.class, map);
        SysConfigFiles configFiles = entity.getEntity();
        if (configFiles != null) {
            filesService.update(configFiles);
            resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, "保存成功！");
        } else {
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_PARAMS_CODE, "文件丢失了！");
        }
        return resultMap;
    }
    
    @ResponseBody
    @RequestMapping(value = "/uploadFiles.do")
    public Map<String, Object> addFiles(@RequestParam(value = "file", required = false) MultipartFile fileinfo, @RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (fileinfo != null) {
            try {
            	SysConfigFiles configFiles = new SysConfigFiles();
                Long fileSize = fileinfo.getSize();
                byte[] arrays = fileinfo.getBytes();
                File f = getFile(arrays, request.getSession().getServletContext().getRealPath("/"), fileinfo.getOriginalFilename());
                InputStream inputStream = fileinfo.getInputStream();
                byte[] bytes = IOUtils.toByteArray(inputStream);
                // 校验md5
                String md5 = DigestUtils.md5Hex(bytes);
                SysConfigFiles oldConfigFiles = filesService.findByMd5(md5);
                if (oldConfigFiles == null) {
                    //执行上传操作
                    String url = common2(f);
                    if (StringUtils.isNoneBlank(url)) {
                        configFiles.setFilesUrl(url);
                        configFiles.setFilesMd5(md5);
                        configFiles.setFilesSize(fileSize.intValue());
                        configFiles.setCreateUserBy(getAdmin().getId());
                        configFiles.setCreateTime(new Date());
                        
                        //进行ipa和apk文件解析，提取app信息(获取包名和版本信息等)
                        Map<String, String> appInfoMap = Icon.getParams(null, f.getAbsolutePath());
                        //检查APP及版本
                        if (appInfoMap!=null&&appInfoMap.size() > 0&&appInfoMap.get("appType")!=null&&!String.valueOf(appInfoMap.get("appType")).equals("")) {
                        	configFiles.setAppPackageName(appInfoMap.get("package"));
                        	System.out.println("apk的包名字是："+appInfoMap.get("package"));
                        	configFiles.setAppVersion(appInfoMap.get("versionCode"));
                        	configFiles.setAppVersionCode(appInfoMap.get("versionName"));
                        	configFiles.setAppType(Integer.parseInt(String.valueOf(appInfoMap.get("appType"))));
                        	Map<String,String> paramMap = new HashMap<>();
                        	paramMap.put("files_url", url);
                        	paramMap.put("app_package_name", appInfoMap.get("package"));
                        	paramMap.put("app_version", appInfoMap.get("versionCode"));
                        	paramMap.put("app_version_code", appInfoMap.get("versionName"));
                        	String downloadUrl = PlistUtil.writeToFile(paramMap, request);
                        	configFiles.setDownloadUrl("itms-services://?action=download-manifest&url="+downloadUrl.replace("http:", "https:"));
                        }
                        if (null != f && f.exists()) {
                            f.delete();
                        }
                        resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, configFiles);
                    } else {
                        resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, "服务器异常");
                    }
                } else {
                    resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, "你已经上传过这个文件了");
                }
            } catch (Exception e) {
                LOGGER.error("上传失败 …… ", e);
                resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, null);
            }
            
        } else {
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_PARAMS_CODE, "文件丢失了");
        }
        return resultMap;
    }

    @ResponseBody
    @RequestMapping("/delFile")
    public Map<String, Object> delFile(@RequestParam(value = "id", required = true) Integer id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            filesService.delById(id);
            resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, null);
        } catch (Throwable e) {
            LOGGER.error("删除失败.", e);
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_500_CODE, null);
        }
        return resultMap;
    }

    
/*	/**
	 * 单文件上传
	 * 
	 * @param file
	 * @param response
	 * @throws Exception
	 *//*
	private String common(File f, SysConfigFiles configFiles) throws Exception {
		FastdfsClient fastdfsClient = FastdfsClientFactory.getFastdfsClient();
		String url = fastdfsClient.upload(f);
		if (null != f && f.exists()) {
			f.delete();
		}
		return url;
	}*/

	/**
	 * 单文件上传(上传完成后不需要删除临时文件)
	 * 
	 * @param file
	 * @param response
	 * @throws Exception
	 */
	private String common2(File f) throws Exception {
        String original = f.getName();
        int index = original.lastIndexOf(".");
        String indexStr =  original.substring(index);
        String url = FtpUtils.uploadFile(UUID.randomUUID().toString()+indexStr,f);
        return url;
	}

    /**
     * 根据byte数组，生成文件
     */
    public static File getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
//            file = new File(filePath + "\\" + fileName);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }
    
}
